<template>
  <el-card>
    <h2 class="mb-4">课题申请记录</h2>

    <el-select
      v-model="topicId"
      placeholder="选择课题"
      @change="fetchApplications"
      class="mb-4"
      clearable
    >
      <el-option
        v-for="topic in topicOptions"
        :key="topic.id"
        :label="topic.title"
        :value="topic.id"
      ></el-option>
    </el-select>

    <el-table v-loading="loading" :data="applicationList" border style="width: 100%">
      <el-table-column prop="applicant_id" label="申请人ID" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" :formatter="formatStatus" width="120"></el-table-column>
      <el-table-column prop="created_at" label="申请时间" width="180" :formatter="formatDate"></el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" @click="viewApplicationDetail(scope.row)">查看详情</el-button>
          <el-button 
            size="small" 
            type="primary" 
            @click="contactApplicant(scope.row)"
            v-if="scope.row.applicant_id"
          >
            联系申请人
          </el-button>
          <el-button
            size="small"
            type="success"
            @click="handleApprove(scope.row.id)"
            v-if="scope.row.status === 'pending'"
          >
            同意
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleReject(scope.row.id)"
            v-if="scope.row.status === 'pending'"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="mt-4"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :total="pagination.total"
      @current-change="handlePageChange"
      layout="prev, pager, next, jumper"
    />

    <!-- 申请详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="申请详情" width="60%">
      <el-descriptions v-if="currentApplication" :column="1" border>
        <el-descriptions-item label="申请ID">{{ currentApplication.id }}</el-descriptions-item>
        <el-descriptions-item label="申请人ID">{{ currentApplication.applicant_id }}</el-descriptions-item>
        <el-descriptions-item label="课题ID">{{ currentApplication.project_id }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ formatStatus(currentApplication) }}</el-descriptions-item>
        <el-descriptions-item label="申请时间">{{ formatDate(currentApplication.created_at) }}</el-descriptions-item>
        <el-descriptions-item label="求职信">
          <pre class="whitespace-pre-wrap">{{ currentApplication.cover_letter }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="简历">
          <a v-if="currentApplication.resume" :href="currentApplication.resume" target="_blank" class="text-blue-500">查看简历</a>
          <span v-else class="text-gray-400">无</span>
        </el-descriptions-item>
        <el-descriptions-item label="作品集">
          <a v-if="currentApplication.portfolio" :href="currentApplication.portfolio" target="_blank" class="text-blue-500">查看作品集</a>
          <span v-else class="text-gray-400">无</span>
        </el-descriptions-item>
        <el-descriptions-item label="动机">
          <pre class="whitespace-pre-wrap">{{ currentApplication.motivation }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="资质说明">
          <pre class="whitespace-pre-wrap">{{ currentApplication.qualifications }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="研究计划">
          <pre class="whitespace-pre-wrap">{{ currentApplication.research_plan }}</pre>
        </el-descriptions-item>
        <el-descriptions-item label="反馈" v-if="currentApplication.review_comment">
          {{ currentApplication.review_comment }}
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { Application, Project } from '@/api/enterpriseTypes';
import {

  getMyProjects,
  getApplications,
  updateApplicationStatus,
  getApplicationDetail,
  ApplicationStatus,
  ProjectStatus
} from '@/api/enterpriseTypes';

const route = useRoute();
const router = useRouter();

// 分页参数
const pagination = ref({
  page: 1,
  size: 10,
  total: 0
});

// 数据
const topicOptions = ref<Project[]>([]);
const applicationList = ref<Application[]>([]);
const loading = ref(false);
const topicId = ref<number | null>(route.query.topicId ? Number(route.query.topicId) : null);

// 申请详情
const detailDialogVisible = ref(false);
const currentApplication = ref<Application | null>(null);

// 格式化日期
const formatDate = (cellValue: any) => {
  return cellValue ? new Date(cellValue).toLocaleString() : '';
};

// 状态格式化
const formatStatus = (row: Application) => {
  const statusMap: Record<string, string> = {
    [ApplicationStatus.Pending]: '待审核',
    [ApplicationStatus.Accepted]: '已通过',
    [ApplicationStatus.Rejected]: '已拒绝',
    [ApplicationStatus.Withdrawn]: '已撤回'
  };
  return statusMap[row.status as string] || row.status;
};

// 获取企业课题（用于下拉选择）
const fetchTopics = async () => {
  try {
    loading.value = true;
    const res = await getMyProjects();
    topicOptions.value = res.data?.filter((item: Project) => item.status !== ProjectStatus.Closed) || [];
    
    // 如果没有从路由参数获取到topicId，且课题列表不为空，则设置第一个课题为默认值
    if (!topicId.value && topicOptions.value.length > 0) {
      topicId.value = topicOptions.value[0].id;
      fetchApplications(); // 自动加载该课题的申请列表
    }
  } catch (error) {
    ElMessage.error('获取课题列表失败');
  } finally {
    loading.value = false;
  }
};
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    pending: '待审核',
    accepted: '已通过',
    rejected: '已拒绝',
    withdrawn: '已撤回'
  }
  return statusMap[status] || status
}
const fetchApplications = async () => {
  if (!topicId.value) {
    applicationList.value = [];
    return;
  }

  loading.value = true;
  try {
    const params = {
      project_id: topicId.value,
      page: pagination.value.page,
      size: pagination.value.size
    }
    const response = await getApplications(params)
    
    applicationList.value = (response as any).data.map((app: any) => ({
      ...app,
      topicTitle: app?.project?.title || '未知课题',
      enterprise: app?.project?.enterprise_id?.toString() || '未知企业',
      applyTime: formatDate(app.apply_date || app.created_at || ''),
      statusText: getStatusText(app.status),
      feedback: app.review_comment || '',
      start_date: formatDate(app.start_date || ''),
      end_date: formatDate(app.end_date || '')
    }))
    pagination.value.total = response.total || 0;
  } catch (error) {
    ElMessage.error('获取申请记录失败');
  } finally {
    loading.value = false;
  }
};

// 分页变化
const handlePageChange = () => {
  fetchApplications();
};

// 查看申请详情
const viewApplicationDetail = async (row: Application) => {
  try {
    loading.value = true;
    const res = await getApplicationDetail(row.id as number);
    currentApplication.value = res.data || null;
    detailDialogVisible.value = true;
  } catch (error) {
    ElMessage.error('获取申请详情失败');
  } finally {
    loading.value = false;
  }
};

// 处理申请状态更新
const updateApplication = async (id: number, status: ApplicationStatus) => {
  try {
    await ElMessageBox.prompt('请输入反馈意见', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputType: 'textarea',
      inputPlaceholder: '请输入反馈意见...'
    }).then(async ({ value }) => {
      await updateApplicationStatus(id, {
        status,
        feedback: value
      });
      ElMessage.success(`操作成功，申请已${status === ApplicationStatus.Accepted ? '通过' : '拒绝'}`);
      fetchApplications();
      detailDialogVisible.value = false;
    });
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败');
    }
  }
};

// 同意申请
const handleApprove = async (id: number) => {
  await updateApplication(id, ApplicationStatus.Accepted);
};

// 拒绝申请
const handleReject = async (id: number) => {
  await updateApplication(id, ApplicationStatus.Rejected);
};

// 联系申请人
const contactApplicant = (application: Application) => {
  if (!application.applicant_id) {
    ElMessage.warning('无法获取申请人信息');
    return;
  }
  
  // 跳转到聊天页面，并传递申请人用户ID
  router.push({
    path: '/chat',
    query: {
      userId: application.applicant_id,
      userName: application.applicant?.username || `申请人(${application.applicant_id})`,
      topicTitle: application.topicTitle || ''
    }
  });
};

onMounted(() => {
  fetchTopics();
  if (topicId.value) {
    fetchApplications();
  }
});
</script>

<style scoped>
/* 保持原有样式不变 */
</style>
